package mathExpEvaluator.model.operator;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mathExpEvaluator.model.MathValue;
import mathExpEvaluator.model.Operant;
import mathExpEvaluator.model.Operator;
import mathExpEvaluator.model.exception.InvalidMathValueException;

public class DivideOperator implements Operator {
	private final OperatorPriority priority;
	private final int priorityLevel = PRIORITY_LEVEL_MULTIPLY;

	private final Pattern belongedOperantPattern = Pattern
			.compile("(-?\\d+(?:\\.\\d+)?)\\/(-?\\d+(?:\\.\\d+)?)");
	
	public DivideOperator(int bracketCount, int position) {
		this.priority = new OperatorPriority(bracketCount, priorityLevel,
				position);
	}

	public MathValue apply(List<MathValue> operants) {
		MathValue v1 = operants.get(0);
		MathValue v2 = operants.get(1);
		if (v1.getValue() instanceof Integer
				&& v2.getValue() instanceof Integer) {
			return new MathValue(new Integer(v1.integerValue()
					/ v2.integerValue()));
		} else {
			return new MathValue(
					new Double(v1.doubleValue() / v2.doubleValue()));
		}
	}

	public String toString() {
		return "/";
	}

	public OperatorPriority getPriority() {
		return this.priority;
	}

	public int getPriorityLevel() {
		return this.priorityLevel;
	}

	public Operant getBelongedOperant(String exp) throws InvalidMathValueException{
		List<MathValue> values = new ArrayList<MathValue>();
		Matcher matcher = belongedOperantPattern.matcher(exp);
		if (matcher.find()) {
			values.add(new MathValue(matcher.group(1)));
			values.add(new MathValue(matcher.group(2)));
			Operant operant = new Operant(values, this);
			return operant;
		} else
			return null;
	}

	public String getStringForm(List<MathValue> values) {
		String value1 = values.get(0).toString();
		String value2 = values.get(1).toString();
		return value1+this.toString()+value2;
	}

}
